/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import http from '@ohos.net.http';

var temp = new Array()

export class ReConnect {
    removeTemp(obj: ESObject) {
        let id = obj.id;
        //将请求记录从 temp 中去掉
        for (var index = 0; index < temp.length; index++) {
            if (id == temp[index].id) {
                temp.slice(index, 1);
            }
        }
    }

    reconnect(obj: ESObject) {
        var id = obj.id;
        //这可以写更多的重连逻辑，比如 每次重连间隔的时间增加
        if (obj.reloadtimes == obj.retryTimes - 1) {
            //将请求记录从 temp 中去掉
            this.removeTemp(obj);
        } else {
            obj.reloadtimes++;
            setTimeout(() => {
                this.request(obj.id, obj.url, obj.options, obj.retryTimes, obj.callback);
            }, obj.reloadtimes * 1000); //每次间隔时间递增
        }
    }

    request(id: number, url: string, options: ESObject, retryTimes: number, callback: Function) {
        //保存每一次请求的信息 如果请求失败，进行重连。重连的时候需要上一次的请求信息
        let RequestObj = {
            id: id,
            url: url,
            options: options,
            callback: callback,
            reloadtimes: 0,
            retryTimes: retryTimes
        };
        //判断是否已经存在 缓存中了,存在则跳过
        let exist = false;
        for (let key in temp) {
            if (id == temp[key].id) {
                exist = true;
                RequestObj = temp[key];
                break;
            }
        }
        //不存在缓存中则插入
        if (!exist) {
            temp.push(RequestObj);
        }

        let httpRequest = http.createHttp()
        httpRequest.request(url,
            options, (err, data) => {
                let _obj = RequestObj;
                if (err) {
                    this.reconnect(_obj);
                } else {
                    this.removeTemp(_obj);
                }
                callback(err, data)
                httpRequest.destroy()
            })
    }
}